# -*- coding: utf8 -*-

from bottle import run, route, abort, redirect, view, static_file
from bottle import get, post, request, response
from bottle import jinja2_view as jview
import urllib
from blog import *
from auth import CookieUser
from ui import create_pagination
from utils import to_utf8, to_str, to_time, now
from cache import cached
from forms import *
import datetime

@cached(key='front', minutes=5)
def get_latest_posts(count=7):
	service = BlogService()
	return service.get_posts(page=1, 
		pagesize=count, only_published=True)


@cached(key='front', minutes=3)
def get_latest_comments(count=9):
	service = BlogService()
	return service.get_comments(page=1, 
		pagesize=count, only_published=True)


@cached(key='front', minutes=2)
def get_links():
	service = BlogService()
	return service.get_links()


@cached(key='front', minutes=10)
def get_users():
	service = BlogService()
	return service.get_users(only_enabled_users=True)


def front_view(view_func):
	'''This is a decorator'''
	def wrap(*args, **kargs):
		links = get_links()
		latest_posts, has_more = get_latest_posts()
		latest_comments, has_more = get_latest_comments()
		viewdata = view_func(*args, **kargs)
		viewdata.update({
			'links': links,
			'latest_posts': latest_posts,
			'latest_comments': latest_comments
		})
		return viewdata
	return wrap


# ```````````````````````````````````````````````````````

def handle_rss_output(userid=0):
	response.headers['content-type'] = 'text/xml'
	service = BlogService()
	posts, more_items = [], False
	if userid>0:
		blog = service.get_blog(userid=userid)
		posts, more_items = blog.get_posts(page=1, pagesize=7, only_published=True)
	else:
		posts, more_items = get_latest_posts()
	latest_post = max(posts, key=lambda p: p.lastmodified_dt)
	latest_date = latest_post.createdate_dt if latest_post else now()
	rss = []
	rss.append(u'<?xml version="1.0" ?>')
	rss.append(u'<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">')
	rss.append(u'<channel>')
	rss.append(u'<title>Bluemask Blog</title>')
	rss.append(u'<link>http://bluemask.net/</link>')
	rss.append(u'<description>来自bluemask.net的最新blog发布</description>')
	rss.append(u'<pubDate>%s</pubDate>' % latest_date)
	rss.append(u'<language>zh-CN</language>')
	rss.append(u'<copyright>Copyright 2011 bluemask.net.</copyright>')
	for p in posts:
		rss.append(u'<item>')
		rss.append(u'<title><![CDATA[%s]]></title>' % p.subject)
		rss.append(u'<dc:creator>%s</dc:creator>' % p.userlabel)
		rss.append(u'<description><![CDATA[%s]]></description>' % p.rss_content) 
		rss.append(u'<link><![CDATA[http://bluemask.net/p/%s/]]></link>' % p.id) 
		rss.append(u'<pubDate>%s</pubDate>' % p.createdate_dt)
		rss.append(u'</item>')
	rss.append(u'</channel>')
	rss.append(u'</rss>')	
	return u'\r\n'.join(rss)

@get('/rss/')
@get('/rss')
def rss_index():
	return handle_rss_output(userid=0)

@get('/user/:userid#\d+#/rss/')
@get('/user/:userid#\d+#/rss')
def user_rss_index(userid):
	return handle_rss_output(userid=userid)
	

@route('/')
@jview('index')
@front_view
def index():
	user = CookieUser(request=request)
	service = BlogService()
	# posts
	pageindex = request.GET.get('page') or ''
	pageindex = int(pageindex) if pageindex.isdigit() else 1
	posts, has_more = service.get_posts(page=pageindex, 
		pagesize=7, only_published=True)
	pagemarks = create_pagination(current=pageindex, 
		has_more_pages=has_more)
	return {
		'user': user,
		'title':"Bluemask Blog",
		'posts': posts,
		'pagemarks': pagemarks
	}

@route('/users/')
@jview('users')
@front_view
def list_users():
	user = CookieUser(request=request)
	all_users = get_users()
	return {
		'user': user,
		'title': u"所有用户",
		'all_users': all_users
	}


@get('/comments/submit/')
@post('/comments/submit/')
@jview('comment_form')
@front_view
def submit_new_comment():
	user = CookieUser(request=request)
	service = BlogService()
	postid = request.POST.get('postid') or ''
	postid = int(postid) if postid.isdigit() else 0
	post = service.get_post(postid, only_published=True) if postid else None
	form = CommentForm(request=request, submitlabel='发表评论')
	if not post:
		form.result['msg'] = u'文章不存在，无法发布评论。'
		form.result['result'] = False
	if form.validate() and post is not None:
		data = form.data
		comment = Comment()
		comment.userid = post.userid
		comment.postid = post.id
		comment.parentid = 0
		comment.author = data['author']
		comment.email = data['email']
		comment.sourceurl = data['url']
		comment.clientip = request.environ.get('REMOTE_ADDR') or ''
		comment.content = data['comment']
		comment.createdate = to_time(now())
		comment.status = 10
		comment.upvote = 0
		comment.downvote = 0
		comment.save()
		form.result['result'] = True
		form.result['msg'] = u'评论已成功发布。'
		form.redirect = ('/p/%s/#comments' % post.id, u'正在返回...')
	return {
		'user': user,
		'title': u'发表评论',
		'subtitle': u'发表评论',
		'form': form,
		'post': post
	}


@route('/comments/')
@jview('comment_list')
@front_view
def list_comments():
	user = CookieUser(request=request)
	service = BlogService()
	pageindex = request.GET.get('page') or ''
	pageindex = int(pageindex) if pageindex.isdigit() else 1
	comments, has_more = service.get_comments(page=pageindex, 
		pagesize=24, only_published=True)
	pagemarks = create_pagination(current=pageindex, 
		has_more_pages=has_more)
	return {
		'user': user,
		'title': u'评论',
		'subtitle': u'评论',
		'comments': comments,
		'pagemarks': pagemarks
	}


@route('/search/')
@jview('search_results')
@front_view
def search_posts():
	user = CookieUser(request=request)
	service = BlogService()
	pageindex = request.GET.get('page') or ''
	pageindex = int(pageindex) if pageindex.isdigit() else 1
	keywords = to_utf8(request.GET.get('q') or '')
	# print isinstance(keywords, str)
	posts, has_more = service.get_posts(page=pageindex, 
		pagesize=24, only_published=True, keywords=keywords)
	pagemarks = create_pagination(current=pageindex, 
		has_more_pages=has_more)
	def set_page_link(mark):
		if mark.get('is_link'):
			mark['url'] = u'/search/?%s' % urllib.urlencode({'page':mark['index'], 'q':to_str(keywords)})
		return mark
	map(set_page_link, pagemarks)
	return {
		'user': user,
		'title': u'查找结果',
		'subtitle': u'查找结果: "%s"' % keywords if keywords else u'查找结果',
		'posts': posts,
		'pagemarks': pagemarks
	}


@route('/list/')
@jview('post_list')
@front_view
def list_posts():
	user = CookieUser(request=request)
	service = BlogService()
	pageindex = request.GET.get('page') or ''
	pageindex = int(pageindex) if pageindex.isdigit() else 1
	posts, has_more = service.get_posts(page=pageindex, 
		pagesize=16, only_published=True)
	pagemarks = create_pagination(current=pageindex, 
		has_more_pages=has_more)
	return {
		'user': user,
		'title': u'列表浏览',
		'subtitle': u'列表浏览',
		'posts': posts,
		'pagemarks': pagemarks,
		'rss_link': ''
	}


@route('/user/:userid#\d+#/')
@jview('post_list')
@front_view
def list_user_posts(userid):
	user = CookieUser(request=request)
	service = BlogService()
	pageindex = request.GET.get('page') or ''
	pageindex = int(pageindex) if pageindex.isdigit() else 1
	blog = service.get_blog(userid=userid)
	bloguser = blog.get_owner()
	posts, has_more = blog.get_posts(page=pageindex, 
		pagesize=16, only_published=True)
	pagemarks = create_pagination(current=pageindex, 
		has_more_pages=has_more)
	return {
		'user': user,
		'title': u'%s发布的文章' % bloguser.namealias if bloguser else 'u列表浏览',
		'subtitle': u'%s发布的文章' % bloguser.namealias if bloguser else 'u列表浏览',
		'posts': posts,
		'pagemarks': pagemarks,
		'rss_link': u'/user/%s/rss/' % userid
	}


	
@route('/p/:postid#\d+#/')
@jview('view_post')
@front_view
def view_post(postid):
	user = CookieUser(request=request)
	service = BlogService()
	post = service.get_post(postid, only_published=True)
	post_user = None
	if post:
		post_user = service.get_blog(userid=post.userid).get_owner()
	comments, more_comments = post.get_comments(pagesize=0) if post else ([],False)
	if len(comments) != post.commentcount:
		post.commentcount = len(comments)
		post.save()
	return {
		'user': user,
		'title': "Bluemask Blog" if not post else post.subject,
		'posts': (post, ),
		'post_user': post_user,
		'comments': comments
	}


@get('/post:postid#\d+#:post_desc#[\w]*?#.aspx')
def handle_old_post_url(postid, post_desc=None):
	return redirect('/list/')

@get('/test')
@get('/test/')
def make_a_test():
	#response.headers['content-type'] = 'text/plain'
	#service = BlogService()
	#post = service.get_post(postid=1210)
	#return post.brief
	return 'just a test.'




